const express = require('express');
const router = express.Router();
const { query, run } = require('../../db.js'); 

// 获取所有事件
router.get('/', async (req, res) => {
    try {
        const page = parseInt(req.query.page) || 1;
        const limit = parseInt(req.query.limit) || 10;
        const offset = (page - 1) * limit;
        
        const events = await query(
            'SELECT * FROM events ORDER BY created_at DESC LIMIT ? OFFSET ?',
            [limit, offset]
        );
        
        res.json({
            success: true,
            data: events,
            page: page,
            limit: limit
        });
    } catch (error) {
        console.error('获取事件列表错误:', error);
        res.status(500).json({
            success: false,
            error: '获取事件失败'
        });
    }
});

// 获取单个事件
router.get('/:id', async (req, res) => {
    try {
        const event = await query(
            'SELECT * FROM events WHERE id = ?',
            [req.params.id]
        );
        
        if (!event || event.length === 0) {
            return res.status(404).json({
                success: false,
                error: '事件不存在'
            });
        }
        
        res.json({
            success: true,
            data: event[0]
        });
    } catch (error) {
        console.error('获取事件详情错误:', error);
        res.status(500).json({
            success: false,
            error: '获取事件详情失败'
        });
    }
});

module.exports = router;